package com.lzh.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author zhehen.lu
 * @date 2025/8/3 14:16
 */
public class EasyExcelLocalDateConverter implements Converter<LocalDate> {
    public EasyExcelLocalDateConverter() {
    }

    @Override
    public Class<LocalDate> supportJavaTypeKey() {
        return LocalDate.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDate convertToJavaData(ReadConverterContext<?> context) throws Exception {
        ReadCellData<?> cellData = context.getReadCellData();
        if (cellData.getType().equals(CellDataTypeEnum.NUMBER)) {
            LocalDate localDate = LocalDate.of(1900, 1, 1);
            localDate = localDate.plusDays(cellData.getNumberValue().longValue() - 2L);
            return localDate;
        } else {
            return cellData.getType().equals(CellDataTypeEnum.STRING) ? LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd")) : null;
        }
    }

    @Override
    public WriteCellData<String> convertToExcelData(WriteConverterContext<LocalDate> context) throws Exception {
        return new WriteCellData(((LocalDate)context.getValue()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    }
}
